﻿CREATE PROCEDURE [maint].[GetCheckDbScheduleStatus]
@DbName [sysname], @CheckDbRequired BIT OUTPUT, @CheckPointDate DATETIME=NULL, @OutputDiagnostics BIT=0
AS
BEGIN
	SET NOCOUNT ON

	DECLARE @RC int, @ERROR int
	SET @RC = 0

	IF(@OutputDiagnostics = 1)
		BEGIN
			PRINT OBJECT_NAME(@@PROCID)
			PRINT N'	@DbName = N''' + ISNULL(@DbName,N'NULL') + ''''
			PRINT N'	@CheckPointDate = N''' + ISNULL(CAST(@CheckPointDate AS nvarchar),N'NULL') + ''''
		END

	IF(@CheckPointDate IS NULL)
		SET @CheckPointDate = GETDATE()

	SET DATEFIRST 1

	SELECT
		@CheckDbRequired =
			(CASE
				WHEN ([CheckDbWeekSchedule] & POWER(2, DATEPART(dw, @CheckPointDate) -1)) = 0 THEN 0
				WHEN ([CheckDbDaySchedule] & POWER(2, DATEPART(hh, @CheckPointDate) - 1)) = 0 THEN 0
				ELSE 1
			END)
	FROM [config].[DbMaintenance]
	WHERE ([DbName] = @DbName)
	SET @ERROR = @@ERROR
	IF(@ERROR <> 0)
		GOTO ERROR_HANDLER

	GOTO EXIT_PROC

ERROR_HANDLER:
	IF(@RC = 0)
		SET @RC = @ERROR

EXIT_PROC:
	RETURN(@RC)
END